<template>
  <div class="todo-header">
    <form @submit.prevent='addTodo'>
      <!--绑定键盘事件keyup.enter -->
      <input type="text" placeholder="请输入你的任务名称，按回车键确认" v-model="text" @keydown.prevent.enter="submit" />
      <button type="submit" ref="btn">添加</button>
    </form>
  </div>
</template>

<script>
import { nanoid } from 'nanoid'
export default {
  name: 'MyHeader',
  props: ['addTodos'],
  data() {
    return {
      text: '',
      btn: null
    }
  },
  methods: {
    submit() {
      this.$refs.btn.click()
    },
    addTodo() {
      // 校验输入的内容
      if (this.text.trim() === '') {
        alert('输入不能为空')
        return;
      } else if (this.text.trim().length > 50) {
        alert('输入不能超过50个字符')
        return;
      }
      // 将用户的输入包装成一个对象
      const todoObj = { id: nanoid(), title: this.text, done: false };
      // 调用父组件传过来的函数，往数组中添加一个事件对象
      this.addTodos(todoObj);
      this.text = '';// 添加完后将输入框清空
    }
  }
};
</script>

<style scoped>
form {
  display: flex;
  align-items: center;
}

form button {
  display: none;
  width: 82px;
  height: 37px;
  margin-left: 4px;
  font-weight: 500;
  outline: none;
  transition: .1s;
  color: #409eff;
  border-radius: 5px;
  box-sizing: border-box;
  user-select: none;
  background-color: #ecf5ff;
  border: 1px solid #a0cfff;
}

.todo-header input {
  flex: 1;
  height: 28px;
  font-size: 14px;
  border: 1px solid #ccc;
  border-radius: 4px;
  padding: 4px 7px;
}

.todo-header input:focus {
  outline: none;
  border-color: rgba(82, 168, 236, 0.8);
  box-shadow: inset 0 1px 1px rgba(0, 0, 0, 0.075), 0 0 8px rgba(82, 168, 236, 0.6);
}
</style>